package com.weblearning.tliasweb.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.weblearning.tliasweb.pojo.Result;
import com.weblearning.tliasweb.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


@Slf4j
@Component  //Bean对象
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override //目标资源运行前  true就是放行  false就是拦截
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        System.out.println("preHandle");

        //包含了url 则是登录操作 直接放行
        String url = req.getRequestURL().toString();
        log.info("请求url" +url);

        if(url.contains("login")){
            log.info("登录放行 ");
            return true;
        }

        String jwt=req.getHeader("token");

        //判断token 是空？
        if(!StringUtils.hasLength(jwt)){
            log.info("请求头token为空 登录失败");
            Result error= Result.error("NOT_LOGIN");
            String noLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(noLogin);
            return false;
        }

        //判断token true?
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token错误");
            Result error = Result.error("token错误");
            String noLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(noLogin);
            return false;
        }

        //放行
        log.info("token正确 放行");
        return true;
    }

    @Override//运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override//最后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
